import { reactive } from "vue";
import type { GlobalDataProps } from "./propsType";
import axios from "@/api/axios";
import router from "@/router";
const _value: GlobalDataProps = {
  error: { status: false },
  token: localStorage.getItem("token") || "",
  isLoading: false,
  user: { isLogin: false },
};
// vue响应数据
const reactiveState = reactive<GlobalDataProps>(_value);
// 做拦截设置
const state = new Proxy(reactiveState, {
  get<T>(oTar: T, sKey: keyof T) {
    return oTar[sKey];
  },
  // 做设值拦截
  set(oTar, sKey, sVal) {
    console.log("没有调用store的自身方法修改值， 无效修改");
    return true;
  },
});
const store = {
  debug: false,
  _value,
  state,
  setState(prop: keyof GlobalDataProps, newValue: any) {
    if (this.debug) {
      console.log(`set ${prop}`, newValue);
    }
    console.log("setState", prop, reactiveState[prop]);
    reactiveState[prop] = newValue;
  },
  loginAction(rawData) {
    const { token } = rawData;
    reactiveState.token = token;
    localStorage.setItem("token", token);
    axios.defaults.headers.common.Authorization = `Bearer ${token}`;
  },
  logoutAction() {
    const { reuqiredLogin } = router.currentRoute.value.meta;
    reactiveState.token = "";
    reactiveState.user = { isLogin: false };
    localStorage.removeItem("token");
    delete axios.defaults.headers.common.Authorization;
    if (reuqiredLogin) {
      router.push("/");
    }
  },
  fetchUserAction(rawData) {
    reactiveState.user = { isLogin: true, ...rawData };
  },
};
export default store;
